package com.jade.framework.base.lang;

/**
 * CRC16计算。
 *
 * @author sky
 * @version 1.0 14-10-12 上午11:44
 */
public final class CRC16
{
    private short[] crcTable = new short[256];
    private int gPloy = 0xc0c1; // 生成多项式

    private CRC16(int gPloy)
    {
        this.gPloy = gPloy;
        computeCrcTable();
    }

    private short getCrcOfByte(int aByte)
    {
        int value = aByte << 8;

        for (int count = 7; count >= 0; count--) {
            if ((value & 0x8000) != 0) { // 高第16位为1，可以按位异或
                value = (value << 1) ^ gPloy;
            }
            else {
                value = value << 1; // 首位为0，左移
            }

        }
        value = value & 0xFFFF; // 取低16位的值
        return (short)value;
    }

    /*
     * 生成0 - 255对应的CRC16校验码
     */
    private void computeCrcTable()
    {
        for (int i = 0; i < 256; i++) {
            crcTable[i] = getCrcOfByte(i);
        }
    }

    public short getCrc(byte[] data)
    {
        return getCrc(data, 0, data.length);
    }

    public short getCrc(byte[] data, int offset, int length)
    {
        int crc = 0;
        int len = offset + length;
        for (int i = offset; i < len; i++) {
            crc = ((crc & 0xFF) << 8) ^ crcTable[(((crc & 0xFF00) >> 8) ^ data[i]) & 0xFF];
        }
        crc = crc & 0xFFFF;
        return (short)crc;
    }

    public static short getCrc(int gPloy, byte[] data)
    {
        return new CRC16(gPloy).getCrc(data);
    }

    public static short getCrc(int gPloy, byte[] data, int offset, int length)
    {
        return new CRC16(gPloy).getCrc(data, offset, length);
    }
}
